<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 嵌套执行
        let activeEffect

        const bucket = new WeakMap();

        const data = { text: "hello world!" }

        const obj = new Proxy(data, {
            get(target, key) {
                track(target, key)
                return target[key]
            },
            set(target, key, newVal) {
                target[key] = newVal

                trigger(target, key)
            }
        })

        function track(target, key) {
            let depsMap = bucket.get(target)
            if (!depsMap) {
                bucket.set(target, (depsMap = new Map()))
            }
            let deps = depsMap.get(key)

            if (!deps) {
                depsMap.set(key, (deps = new Set()))
            }
            deps.add(activeEffect)
            activeEffect.deps.push(deps)
        }
        function trigger(target, key) {
            const depsMap = bucket.get(target)
            if (!depsMap) return
            const effects = depsMap.get(key)

            const effectsToRun = new Set()
            effects && effects.forEach(effectFn => effectsToRun.add(effectFn))
            effectsToRun.forEach(effectFn => effectFn())
        }

        // 嵌套的effect
        const effectStack = [];

        function effect(fn) {
            const effectFn = () => {
                // 清空当前副作用
                cleanup(effectFn)

                activeEffect = effectFn

                effectStack.push(effectFn)
                fn()

                effectStack.pop()
                activeEffect = effectStack[effectStack.length - 1]
            }
            effectFn.deps = []
            // 触发后再次挂载
            effectFn()
        }

        function cleanup(effectFn) {
            for (let i = 0; i < effectFn.deps.length; i++) {
                const deps = effectFn.deps[i]
                deps.delete(effectFn)
            }
            effectFn.deps.length = 0
        }

        effect(() => {
            console.log('effectFn1 执行')
            effect(function effectFn2() {
                console.log('effectFn2 执行')
                temp2 = obj.bar
            })
            temp1 = obj.foo
        })

        setInterval(() => {
            obj.foo = false
        }, 1000)
    </script>
</body>

</html>